import { FC, useEffect, useState, useRef, useMemo } from 'react';
import QuestionCard, { PropsType } from '../../../components/QuestionCard';
import styles from '../common/index.module.scss';
import { useSearchParams } from 'react-router-dom';
import { useDebounceFn, useRequest, useTitle } from 'ahooks';
import { Typography, Empty, Spin } from 'antd';
import ListSearch from '../../../components/ListSearch';
import { getQuestionListService } from '../../../services/question';
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from '../../../constants';
const List: FC = () => {
  const [searchParams] = useSearchParams();
  console.log('keywords', searchParams.get('keyword'));
  const { Title } = Typography;
  useTitle('小慕问卷 - 我的问卷');
  const [started, setStarted] = useState(false);
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const haveMoreData = total > list.length;
  const loadMoreRef = useRef<HTMLDivElement>(null);
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || '';
  useEffect(() => {
    setList([]);
    setPage(1);
    setTotal(0);
  }, [keyword]);

  const { loading, run: load } = useRequest(
    async () => {
      const data = await getQuestionListService({
        keyword,
        page,
        pageSize: LIST_PAGE_SIZE,
      });
      return data;
    },
    {
      manual: true,
      onSuccess: (res) => {
        const { list: newList = [], total = 0 } = res;
        setList(list.concat(newList));
        setTotal(total);
        setPage(page + 1);
      },
    },
  );

  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const divElement = loadMoreRef.current;
      if (!divElement) return;
      const { bottom } = divElement.getBoundingClientRect();
      if (bottom <= document.body.clientHeight) {
        load();
        setStarted(true);
      }
    },
    {
      wait: 1000,
    },
  );

  useEffect(() => {
    tryLoadMore();
  }, [searchParams, tryLoadMore]);

  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener('scroll', tryLoadMore);
    }
    return () => {
      window.removeEventListener('scroll', tryLoadMore);
    };
  }, [searchParams, tryLoadMore, haveMoreData]);
  const loadMoreElement = useMemo(() => {
    if (!started || loading) return <Spin />;
    else if (!loading && total === 0) return <Empty description="暂无数据" />;
    else if (!haveMoreData) return <span>没有更多了...</span>;
    else return <span>开始加载下一页</span>;
  }, [started, loading, haveMoreData, total]);
  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {list.length > 0 &&
          list.map((question: PropsType) => {
            const { id } = question;
            return <QuestionCard key={id} {...question} />;
          })}
      </div>
      <div className={styles.footer} ref={loadMoreRef}>
        {loadMoreElement}
      </div>
    </>
  );
};
export default List;
